<?php
 /*
  *总后台设备管理模型类
  */
namespace Home\Model; 
use Think\Model;
class DeviceModel extends Model
{
	
	public function index($arg)
	{
		
		$page=!empty($arg['page'])?intval($arg['page']):1; 
		$device=M('device a');
		 //获取所有设备类型
		$devicetype=M('config')->where('id=%d',2)->getField('value');
		$devicetype=unserialize($devicetype);
		
		$where=array();
		//过滤条件
		if(!empty($arg['start']) && !empty($arg['end']) )
		{
			$start=strtotime($arg['start']);
			$end=strtotime($arg['end']);
			$where['a.createtime']=array('between',array($start,$end));
		}
		
		if(!empty($arg['devicecode'])){
			$where['devicecode']=array('like', '%'.$arg['devicecode'].'%');

		}

		if($arg['type'])
		{
			$where['a.tiypeid']=intval($arg['tiypeid']);
		}

		if ($arg['isfen'] !==99 && !empty($arg['isfen']))
		 {
		 	switch ($arg['isfen'])
		 	 {
		 		//未分配机器 ，shipid 为0
		 		case 2:
		 			$where['a.shopid']=array('eq',0);
		 			break;
		 		//已分配机器 ，shipid 不为0
		 		case 1:
		 			$where['a.shopid']=array('neq',0);
		 			break;
		 			
		 	}

		 }
	
		$count=$device->where($where)->count();
		$pagearr= getPageArr($page,C('PAGESIZE'),$count);
		$result=M('device a')->join('left join '.C('DB_PREFIX').'shop_user b on a.shopid=b.shopid')
				->where($where)
		 		->order('a.deviceid desc')
		 		->limit($pagearr['start'],$pagearr['pagesize'])
		 		->getField('a.deviceid,a.devicecode,FROM_UNIXTIME(a.createtime, "%Y-%m-%d %H:%i:%S") as createtime ,a.tiypeid,b.companyname');
 		//echo M()->getLastSql();die;
 		//获取设备类型及是否分配
 		
 		foreach ($result as $key => &$value) {
 			$typeid=intval($value['tiypeid']);
 			
 			$value['devicetype']=$devicetype[$typeid];
 			if(!empty($value['companyname']))
	 		{
	 				$value['isfen']='已分配';

	 		}else
	 		{		$value['companyname']='';
	 				$value['isfen']='未分配';
	 			}
 		}
 		
 		$temp['pagearr']=$pagearr;
 		$temp['devices']=!empty($result)?$result:'';
 		
 		//设置page cookie
 		return $temp;
	}
}